from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP

# 初始化FastMCP服务器
mcp = FastMCP("weather")

# 常量
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"

async def make_nws_request(url: str) -> dict[str, Any] | None:
    """向NWS API发出GET请求，处理错误并返回JSON响应"""
    headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except httpx.RequestError as exc:
            print(f"An error occurred while requesting {url}: {exc}")
            return None
        except httpx.HTTPStatusError as exc:
            print(f"HTTP error occurred: {exc.response.status_code} - {exc.response.text}")
            return None

@mcp.tool()
async def get_forecast() -> str:
    """获取深圳的天气预报。"""
    forecast_data = await make_nws_request(NWS_API_BASE)

    if not forecast_data:
        return "无法获取详细预报。"

    # 将时段格式化为可读预报
    periods = forecast_data["days"]
    forecasts = []
    for period in periods[:5]:  # 只显示接下来的5个时段
        """
        datetime 日期
        tempmax 最高气温
        tempmin 最低气温
        temp 当前气温
        feelslikemax 体感最高气温
        feelslikemin 体感最低气温
        dew 露点
        humidity 湿度
        precip 预期降水量
        precipprob 预期降水概率
        precipcover 预期降水覆盖率
        preciptype 预期气候类型
        windgust 预期风速
        windspeed 风速
        winddir 风向
        cloudcover 云覆盖率
        solarradiation 日照强度
        """
        forecast = f"""
Temperature: {period['temp']}°F
Max Temperature: {period['tempmax']}°F
Min Temperature: {period['tempmin']}°F
Feels Like: {period['feelslike']}°F
Dew Point: {period['dew']}°F
Humidity: {period['humidity']}%
Precipitation: {period['precip']} inches
Precipitation Probability: {period['precipprob']}%
Precipitation Cover: {period['precipcover']}%
Precipitation Type: {period['preciptype']}
Wind Gust: {period['windgust']} mph
Cloud Cover: {period['cloudcover']}%
Solar Radiation: {period['solarradiation']} W/m^2
Wind: {period['windspeed']} {period['winddir']}
Forecast: {period['description']}
"""
        forecasts.append(forecast)

    return "\n---\n".join(forecasts)

@mcp.tool()
async def Fahrenheit2Celsius(fahrenheit: float) -> float:
    """华氏度转摄氏度"""
    return (fahrenheit - 32) * 5 / 9


if __name__ == "__main__":
    # 初始化并运行服务器
    mcp.run(transport="stdio")
